package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.form.CreateOrderRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        // 先向下转型接收下这个context
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();

        // 这个是空的，因为CreateOrderRequest转换成CreateOrderContext的时候并没有这个成员变量
        // 这里通过它的另个成员变量List<CartProductDto>中的productId来给它赋值
        List<Long> productIds = createOrderContext.getBuyProductIds();

        if(CollectionUtils.isEmpty(productIds)){
            productIds = cartProductDtoList.stream().map(u->u.getProductId()).collect(Collectors.toList());
        }
        // 根据大小去排序
        productIds.sort(Long::compareTo);

        // 排序完成需要去扣减库存

        // 锁定库存
        // 因为是通过主键id来锁住的，这个时候是行级锁，其他事务可以对该行进行读取，但不能写入和更新
        List<Stock> stockList= stockMapper.findStocksForUpdate(productIds);

        // 可能没有找到相关库存
        if (CollectionUtils.isEmpty(stockList)) {
            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        if(stockList.size()!=productIds.size()){
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        // 扣减库存
        for (CartProductDto cartProductDto : cartProductDtoList) {

            // 获取扣减库存需要的参数
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();

            // 判断订单中的商品数量是否超出限购数量
            Stock targetStock = stockMapper.selectStock(productId);
            if (productNum > targetStock.getRestrictCount()) {
                throw new BizException(OrderRetCode.PRODUCTNUM_OUT_OF_RESTRICTCOUNT.getCode(),
                        OrderRetCode.PRODUCTNUM_OUT_OF_RESTRICTCOUNT.getMessage());
            }

            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);

            stockMapper.updateStock(stock);

        }


        return true;
    }
}